package rmi;

import java.rmi.AlreadyBoundException;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

import toolkit.Global;
	
public class Server
{
	public static final int REGISTRY_PORT = 2004;
	
	public static final String HIBERNATE_CONFIG = "akaryan";
	
	static public Registry registry;
	
	@PersistenceContext
	private EntityManager entityManager;
	
	public Server() throws RemoteException
	{
		// Only the remote objects interact with the database,
		// so the entity manager will be stored here.
		entityManager = Persistence.createEntityManagerFactory(HIBERNATE_CONFIG).createEntityManager();
		
		System.setProperty("java.security.policy", Global.getUserDir() + "/src/poker.policy");
		
    	System.setSecurityManager(new RMISecurityManager());
    	
    	LocateRegistry.createRegistry(REGISTRY_PORT);
  		
    	registry = LocateRegistry.getRegistry(REGISTRY_PORT);
	}
	
	public void setServerObject(String key, Remote object) throws RemoteException, AlreadyBoundException
	{
		// Since all server remote objects will interact with the database,
		// all of them get a reference to to the entitymanager.
		if (object instanceof rmi.server.Remote)
		{
			((rmi.server.Remote) object).setEntityManager(entityManager);
		}
		
		// The registry and the exported objects can be bind to the same port.
		Remote stub = UnicastRemoteObject.exportObject(object, REGISTRY_PORT);

	    registry.bind(key, stub);
	}
}